package com.aku.config;

import com.aku.pojo.User;
import com.aku.security.UserAuthService;
import com.aku.service.StudentService;
import com.aku.service.UserService;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.rememberme.InMemoryTokenRepositoryImpl;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;


@Configuration
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    @Resource
    private UserAuthService userAuthService;
    @Resource
    UserService userService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        PasswordEncoder encoder = new BCryptPasswordEncoder();
        auth.userDetailsService(userAuthService).passwordEncoder(encoder);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()//首先需要配置哪些请求会被拦截，哪些请求必须具有什么角色才能访问
                .antMatchers("/static/**","/page/auth/**","/api/auth/**").permitAll()//静态资源，使用permitAll来运行任何人访问（注意一定要放在前面）
                .antMatchers("/page/admin/**","api/admin/**").hasRole("admin")
                .antMatchers("/page/user/**","api/user/**").hasRole("user")
                .anyRequest().hasAnyRole("user","admin")
                .and()
                .formLogin()/*配置form表单登录*/
                .loginPage("/page/auth/login")/*登录页面地址 （GET）*/
                .loginProcessingUrl("/page/auth/formLogin")/*form表单的提交地址 （POST）*/
                .successHandler(this::onAuthenticationSuccess)
                .permitAll()/*登录页面允许所有人访问*/
                .and()
                .logout()
                .logoutUrl("/api/auth/logout")
                .logoutSuccessUrl("/login")
                .and()
                .csrf().disable()
                .rememberMe()
                .rememberMeParameter("remember")
                .tokenValiditySeconds(60 * 60 * 24 * 7 )
                .tokenRepository(new InMemoryTokenRepositoryImpl());
    }

    public void onAuthenticationSuccess(HttpServletRequest request,
                                        HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {

        HttpSession session = request.getSession();
        User user = userService.findUserByName(authentication.getName());
        session.setAttribute("user",user);
        if(user.getRole().equals("admin")){
            response.sendRedirect("/page/admin/adminBorrowInfo");
        }else {
            response.sendRedirect("/page/user/stuBorrowInfo");
        }
    }
}
